﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;

namespace WebApplication1
{
    public partial class DownLoadPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserInfo"] == null)
            {
                Response.Write("<script>alert('登录后才能下载文件');location.href='Login.aspx';</script>");
                return;
            }


            //////////////////////////////////////////////////////////////////////////////////////

            //从web.config读取文件上传路径

            string strFileUploadPath = ConfigurationManager.AppSettings["FileUplodePath"].ToLower();

            //从列表框中读取选择的文件

            int iFileId = Convert.ToInt32(Request.QueryString["id"]);

            string strFileName = SQLHelper.getFileNameById(iFileId);
            string strOriginName = SQLHelper.getOriginFileNameById(iFileId);

            //组合成物理路径

            string FullFileName = Server.MapPath(strFileUploadPath + "/") + strFileName;

            FileStream fs = new FileStream(FullFileName, FileMode.Open);

            byte[] bytes = new byte[(int)fs.Length];

            fs.Read(bytes, 0, bytes.Length);

            fs.Close();

            Response.ContentType = "application/octet-stream";

            //通知浏览器下载文件而不是打开

            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(strOriginName, System.Text.Encoding.UTF8));

            Response.BinaryWrite(bytes);


            Response.Flush();

            Response.End();
            ///////////////////////////////////////
        }
    }
}